package com.hexacta.hrs.sandbox.pr.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

import com.hexacta.hrs.sandbox.pr.model.Person;
import com.hexacta.hrs.sandbox.pr.model.Project;
import com.hexacta.hrs.sandbox.pr.service.PersonService;
import com.hexacta.hrs.sandbox.pr.service.ProjectService;
import com.opensymphony.xwork2.ActionSupport;

@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class ProjectAction extends ActionSupport
{
	private static final long serialVersionUID = 1L;
	private List<Person> persons;
	private String selectedLeader;
	private String name;
	private List<Project> projects;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private PersonService personService;
		
	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSelectedLeader() {
		return selectedLeader;
	}

	public void setSelectedLeader(String selectedLeader) {
		this.selectedLeader = selectedLeader;
	}

	public List<Person> getPersons() {
		return persons;
	}

	public void setPersons(List<Person> persons) {
		this.persons = persons;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}
  
	public PersonService getPersonService() {
		return personService;
	}	
	
	public List<Project> getProjects() {
		return projects;
	}

	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}

	public String execute()
	{
	    return SUCCESS;
	}
	
	public String create() {
		//Es el primer pedido
		this.setPersons(this.personService.listAll());
		return SUCCESS;
	}
	
	public String save() {
		//Validacion
		this.Projectvalidate();
		
		if( this.hasFieldErrors() ) {
			this.setPersons(this.personService.listAll());
			return "VALIDATE";
		}
		
		this.getProjectService().addProject(this.personService.findPersonByName(selectedLeader).get(0), name);
		
		return "LIST";
	}
	
	public String list() {
		this.setProjects(projectService.listAll());
		return SUCCESS;
	}
	
	public String remove() {
		return SUCCESS;
	}

	public void Projectvalidate() {
		if( this.name.length() > 8 )
			this.addFieldError("name", "Max name length = 8");
		if( projectService.findProjectByName(this.name).size() != 0 )
			this.addFieldError("name", "Name already in use");
	}
}